package com.alks.function.controller.finance.mtlcosts;

import com.alks.common.aop.ApiRestController;
import com.alks.common.aop.WebLogger;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.number.AmtUtils;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.PcProdStatus2Dto;
import com.alks.function.data.dto.finance.fincons.InboundDetailsDto;
import com.alks.function.data.dto.finance.mtlcosts.OutListDetailDto;
import com.alks.function.data.request.finance.mtlcosts.OutCfmRequest;
import com.alks.function.data.request.finance.mtlcosts.OutListDetailRequest;
import com.alks.function.data.request.finance.mtlcosts.OutListSizeFindRequest;
import com.alks.function.data.request.finance.mtlcosts.OutListTempRequest;
import com.alks.function.service.finance.mtlcosts.IOutListFinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author MS
 * @since 2024/6/25下午3:20
 */
@RestController
@ApiRestController("/mtlCosts")
@Api(value = "财务部", tags = "财务部-材料费用-外发结算作业-4")
@Slf4j
public class OutListFinController {
    @Autowired
    private IOutListFinService service;

    @WebLogger
    @PostMapping("/outListTempQuery")
    @ApiOperation(value = "外发资料查询", tags = "财务部-材料费用-外发结算作业-4")
    public ResponseInfo outListTempQuery(@RequestBody OutListTempRequest request) {
        return service.outListTempQuery(request);
    }

    @WebLogger
    @PostMapping("/outListDetailQuery")
    @ApiOperation(value = "外发明细查询", tags = "财务部-材料费用-外发结算作业-4")
    public ResponseInfo outListDetailQuery(@RequestBody OutListDetailRequest request) {
        return ResponseInfo.ok(service.outListDetailQuery(request));
    }

    @WebLogger
    @PostMapping("/outListSizeQuery")
    @ApiOperation(value = "外发号码明细", tags = "财务部-材料费用-外发结算作业-4")
    public ResponseInfo outListSizeQuery(@RequestBody OutListSizeFindRequest request) {
        return service.outListSizeQuery(request);
    }

    @WebLogger
    @PutMapping("/outListTempCfm")
    @ApiOperation(value = "检核作业", tags = "财务部-材料费用-外发结算作业-4")
    public ResponseInfo outListTempCfm(@RequestBody List<OutCfmRequest> request,
                                       @RequestParam @ApiParam(required = true, value = "0.取消检核 1.检核") Integer type,
                                       @RequestParam(required = false) @ApiParam(value = "结算月份") String financeYymm,
                                       @RequestParam(required = false) @ApiParam(value = "结算方式") String accountName,
                                       @RequestParam Integer retryFlag
    ) {
        return service.outListTempCfm(request,type,financeYymm,accountName,retryFlag);
    }

    @WebLogger
    @PostMapping("/outListFinish/export")
    @ApiOperation(value = "导出结算清单", tags = "财务部-材料费用-外发结算作业-4")
    public void outListFinishExport(@RequestBody OutListDetailRequest request, HttpServletResponse response) {
        request.setPageNum(-1);
        request.setPageSize(-1);
        if (StringUtils.isBlank(request.getFinanceYymm())||StringUtils.isBlank(request.getVendor())){
            throw new ServiceErrorException("请选择结算月份和厂商");
        }
        String year = request.getFinanceYymm().substring(0, 4);
        String month = request.getFinanceYymm().substring(4, 6);
        String dataDate = year + "年" + month + "月";
        String templet = "外发结算清单模版.xls";
        String fileName = "外发结算清单" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + ".xls";
        Map<String, Object> map = service.outListDetailQuery(request);
        List<OutListDetailDto> dtoList = (List<OutListDetailDto>) map.get("dtos");
        if (ArrayUtils.isEmpyt(dtoList)){
            throw new ServiceErrorException("暂无导出数据");
        }
        Map<String,String> otherMap = service.finExportDispose(dtoList);
        otherMap.put("date", dataDate);
        otherMap.put("vendor", request.getVendor());
        try {
            ExcelUtils.creatByTemplate(response, templet, fileName, dtoList,otherMap);
        } catch (Exception e) {
            throw new ServiceErrorException("导出失败");
        }
    }

    @WebLogger
    @PostMapping("/outListDetail/export")
    @ApiOperation(value = "导出", tags = "财务部-材料费用-外发结算作业-4")
    public void outListDetailExport(@RequestBody OutListDetailRequest request, HttpServletResponse response) {
        request.setPageNum(-1);
        request.setPageSize(-1);
        String templet = "外发结算作业_4模版.xls";
        String fileName = "外发结算作业" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + ".xls";
        Map<String, Object> map = service.outListDetailQuery(request);
        List<OutListDetailDto> dtoList = (List<OutListDetailDto>) map.get("dtos");
        if (ArrayUtils.isEmpyt(dtoList)){
            throw new ServiceErrorException("暂无导出数据");
        }
        BigDecimal amtSum = dtoList.stream().map(OutListDetailDto::getAmt).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal qtySum = dtoList.stream().map(OutListDetailDto::getPurQty).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
        OutListDetailDto dto = new OutListDetailDto();
        dto.setAmt(amtSum);
        dto.setPurQty(qtySum);
        dto.setPartName("合计");
        dtoList.add(dto);
        try {
            ExcelUtils.creatByTemplate(response, templet, fileName, dtoList);
        } catch (Exception e) {
            throw new ServiceErrorException("导出失败");
        }
    }

    @WebLogger
    @GetMapping("/outListDetail/back")
    @ApiOperation(value = "厂商/结算月份回显", tags = "财务部-材料费用-外发结算作业-4")
    public ResponseInfo outListDetailBack(@RequestParam(required = false) String vendorSearch,
                                          @RequestParam(required = false) String financeSearch) {
        return ResponseInfo.ok(service.outListDetailBack(vendorSearch,financeSearch));
    }

}